package com.umeox.moto.watch.fitness.data;


import static com.umeox.moto.watch.fitness.data.PedometerDeviceEvent.Action.BOOT;
import static com.umeox.moto.watch.fitness.data.PedometerDeviceEvent.Action.RESET;
import static com.umeox.moto.watch.fitness.data.PedometerDeviceEvent.Action.SHUTDOWN;

import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;

import com.umeox.moto.common.utils.DateUtils;
import com.umeox.moto.watch.fitness.base.BaseApp;
import com.umeox.moto.watch.fitness.utils.CacheImpl;
import com.umeox.moto.watch.fitness.utils.ICache;
import com.umeox.watch.moto.dataservice.DataProvider;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


public class PedometerPresenter implements PedometerContract.Presenter {
    private static final String TAG = "PedometerData";

    private PedometerContract.View mView;
    private PedometerDataSource mPedometerData;
    private Handler mHandler = new Handler();
    private boolean mAlreadyLoaded;

    public PedometerPresenter(PedometerContract.View view) {
        mView = view;
        mPedometerData = new PedometerNodeData(this);
        HandlerThread handlerThread = new HandlerThread("PedometerData_thread");
        handlerThread.start();
    }

    /**
     * 初始化计步数据监听并获取计步数据
     */
    @Override
    public void start() {

        if (mAlreadyLoaded) {
            return;
        }
        mAlreadyLoaded = true;
        mPedometerData.load();
        mHandler.postDelayed(this::loadData, 2000);
    }

    /**
     * 获取计步数据
     */
    public void loadData() {
        mPedometerData.load();
        mHandler.postDelayed(this::loadData, 2000);
    }


    private ContentObserver mStepInfoObserver = new ContentObserver(null) {
        @Override
        public void onChange(boolean selfChange) {
            mHandler.post(PedometerPresenter.this::initPetInfo);
            mHandler.post(() -> {
                initPetInfo();
                mView.onHolderInfoChange();
            });
        }
    };


    private ContentObserver mDistanceUnitObserver = new ContentObserver(null) {
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            mHandler.post(() -> mView.onDistanceUnitChange());
        }
    };

    private void initPetInfo() {
        int target = DataProvider.getPlanValue(5000);
        mView.onStepInfoChange(target == 0 ? 5000 : target);
    }

    /**
     * 取消计步数据监听
     *
     * @param context
     */

    @Override
    public void stop(Context context) {
        Log.w(TAG, "stop: " + context);
        if (context == null) {
            return;
        }
        mAlreadyLoaded = false;
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onStepCountChange(int stepCounts) {
        mView.onStepCountChange(stepCounts);
    }

    @Override
    public void getStepInfo() {
        initPetInfo();
        mPedometerData.getStepInfo();

    }


    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void onPedometerDeviceEvent(PedometerDeviceEvent event) {

        final int action = event.mAction;
        final int todayMillis = DateUtils.getTodayMillis();
        switch (action) {
            case BOOT:
                mPedometerData.resetAndSaveStepCount(todayMillis, todayMillis);
                break;
            case SHUTDOWN:
                mPedometerData.saveTotalStepCount();
                break;
            case RESET:
                int cacheTime = CacheImpl.getInstance().get(ICache.KEY_STEP_TIME, 0);
                mPedometerData.resetAndSaveStepCount(todayMillis, cacheTime);
                break;
        }
    }


    @Override
    public void onCreate() {
        DataProvider.HolderInfoProvider.registerContentObserver(false, mStepInfoObserver);
        mPedometerData.onCreate();
        EventBus.getDefault().register(this);

    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        final ContentResolver contentResolver = BaseApp.getAppContext().getContentResolver();
        contentResolver.unregisterContentObserver(mStepInfoObserver);
        contentResolver.unregisterContentObserver(mDistanceUnitObserver);
        mPedometerData.onDestroy();
    }


}
